import { associationandEntList, getAiStudyEntList, StudyEntSearch, StudyEntType } from '@/api/AiStatisticApi';
// import { EntNoStudySearchParams, noStudyListItem } from '@/api/StatisticsApi/entStudyTable';
import { SelectSearchIpt } from '@/components/SelectSearchIpt';
import { Button, Space } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import type { YmTablePorps } from 'ym-design';
import { YmAddPageLayout, YmTable, type YmAddPageLayoutProps } from 'ym-design';
import { PersonStudyDetailModal } from '../PlanLearnTable/PersonStudyDetail';

type SearchValue = Partial<StudyEntSearch>;
type TableRecord = StudyEntType;
const { PaneItem } = YmAddPageLayout;

function EntPersonStudy() {
  //人员明细
  const personStudyRef = useRef<any>();
  const [planItem, setPlanItem] = useState<any>({
    finishState: undefined,
    aiPlanId: undefined,
    aiCycleId: undefined,
    from: 'detail',
    entId: '',
  });

  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const studyObject =
    searchParam.get('studyObject') && searchParam.get('studyObject') != 'null'
      ? searchParam.get('studyObject')
      : undefined;
  const aiCycleId =
    searchParam.get('aiCycleId') && searchParam.get('aiCycleId') != 'null' ? searchParam.get('aiCycleId') : undefined;
  const aiPlanId =
    searchParam.get('aiPlanId') && searchParam.get('aiPlanId') != 'null' ? searchParam.get('aiPlanId') : '';

  const columns: YmTablePorps<TableRecord, SearchValue>['columns'] = useMemo(
    () => [
      {
        title: '编号',
        dataIndex: 'No',
        key: 'No',
        width: 80,
        render(value) {
          return value < 10 ? '0' + value : value;
        },
      },
      {
        dataIndex: 'entName',
        title: '企业名称',
        key: 'entName',
        width: 200,
        ellipsis: true,
      },
      {
        dataIndex: 'ownerAssociation',
        title: '企业所属协会',
        key: 'ownerAssociation',
        width: 200,
        hidden: studyObject == '2',
        ellipsis: true,
      },
      {
        dataIndex: 'allPersonNum',
        title: '应学人数(人)',
        key: 'allPersonNum',
        width: 100,
      },
      {
        dataIndex: 'studyPersonNum',
        title: '已学人数(人)',
        key: 'studyPersonNum',
        width: 100,
      },
      {
        dataIndex: 'noStudyPersonNum',
        title: '未学人数(人)',
        key: 'noStudyPersonNum',
        width: 100,
        render: (text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  setPlanItem({
                    finishState: 2,
                    aiPlanId: record.aiPlanId,
                    aiCycleId: record.aiCycleId,
                    from: 'detail',
                    entId: record.entId,
                  });
                  personStudyRef.current?.showModal();
                }}
              >
                <span className="safe-edu_table_operation_text">{text || '--'}</span>
              </Button>
            </Space>
          );
        },
      },
      {
        dataIndex: 'studyRatio',
        title: '已学率(%)',
        key: 'studyRatio',
        width: 80,
      },
      {
        title: '操作',
        key: 'action',
        width: 80,
        fixed: 'right',
        render: (text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  setPlanItem({
                    finishState: '',
                    aiPlanId: record.aiPlanId,
                    aiCycleId: record.aiCycleId,
                    from: 'detail',
                    entId: record.entId,
                  });
                  personStudyRef.current?.showModal();
                }}
              >
                <span className="safe-edu_table_operation_text">详情</span>
              </Button>
            </Space>
          );
        },
      },
    ],
    [searchParam],
  );
  const [tableDep, _reFreshTable] = useState<number>();
  const reFreshTable = () => _reFreshTable(Math.random());
  /*获取政协企下拉列表 */
  const GetAssociation = async (e: string) => {
    const data = await associationandEntList({
      aiPlanId: aiPlanId,
      associationName: e,
    });
    let list = [];
    if (data.associationEntList && data.associationEntList.length) {
      list = data.associationEntList.map((v) => ({
        value: v.entName,
        text: v.entName,
      }));
    } else {
      list = [{ value: null, text: '暂无数据', disabled: true }];
    }
    return list;
  };

  /*获取企业下拉列表 */
  const GetEnt = async (e: string) => {
    const data = await associationandEntList({
      aiPlanId: aiPlanId,
      entName: e,
    });
    let list = [];
    if (data.entList && data.entList.length) {
      list = data.entList.map((v) => ({
        value: v.entName,
        text: v.entName,
      }));
    } else {
      list = [{ value: null, text: '暂无数据', disabled: true }];
    }
    return list;
  };

  useEffect(() => {
    reFreshTable();
  }, [aiCycleId, aiPlanId]);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          navigator(-1);
        },
      },
      destroyInactiveTabPane: false,
    }),
    [],
  );

  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem tabKey="tab1" label="计划学习情况" className="pane_tab1">
        <div>
          <div style={{ background: '#fff', width: '100%', height: 'calc(100vh - 118px)', minHeight: '730px' }}>
            <YmTable<TableRecord, SearchValue>
              style={{ minHeight: 650 }}
              searchForm={{
                formItems: [
                  {
                    label: '协会',
                    name: 'associationName',
                    hidden: studyObject == '2',
                    colProps: {
                      span: studyObject == '2' ? 0 : undefined,
                    },
                    children: <SelectSearchIpt placeholder="请选择" searchFun={GetAssociation}></SelectSearchIpt>,
                  },
                  {
                    label: '企业',
                    name: 'entName',
                    children: <SelectSearchIpt placeholder="请选择" searchFun={GetEnt}></SelectSearchIpt>,
                  },
                ],
                span: 6,
              }}
              columns={columns}
              toolBar={false}
              request={async ({ page }, form) => {
                const { current = 1, pageSize = 10 } = page ?? {};
                const data = await getAiStudyEntList(current, pageSize, {
                  aiCycleId: aiCycleId,
                  aiPlanId: aiPlanId,
                  ...form,
                });
                return data;
              }}
              requestOptions={{
                reFreshDep: [tableDep],
                defaultPageSize: 10,
              }}
            />
          </div>
          <PersonStudyDetailModal
            props={planItem}
            innerRef={personStudyRef}
            onChange={() => {}}
          ></PersonStudyDetailModal>
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default EntPersonStudy;
